package piechowicz.szymon.balloonwars;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class BearingController
{
    
    @SuppressWarnings("unused")
    private final Activity activity;
    private final BearingControllerListener listener;
    private final SensorManager sensorManager;
    private final OrientationListener orientationListener;

    public BearingController(Activity activity,
            BearingControllerListener listener)
    {
        this.activity = activity;
        this.listener = listener;
        
        sensorManager = (SensorManager)activity.getSystemService(
                Context.SENSOR_SERVICE);
        orientationListener = new OrientationListener();
    }

    public void resume()
    {
        for (Sensor sensor :
            sensorManager.getSensorList(Sensor.TYPE_ORIENTATION))
        sensorManager.registerListener(orientationListener, sensor,
                SensorManager.SENSOR_DELAY_GAME);
    }
    
    public void pause()
    {
        sensorManager.unregisterListener(orientationListener);
    }
    
    // Classes, interfaces
    
    public interface BearingControllerListener
    {
        
        public void onBearingChanged(double bearing);
        
    }
    
    private class OrientationListener implements SensorEventListener
    {
        
        public void onAccuracyChanged(Sensor sensor, int accuracy)
        {
        }
        
        public void onSensorChanged(SensorEvent event)
        {
            float x = event.values[2];
            float y = event.values[1];
            x = Math.max(Math.min(x, 90), -90);
            double orientation = Math.atan2(y, x);
            if (orientation < 0)
                orientation += Math.PI;
            else
                orientation -= Math.PI;
            listener.onBearingChanged(orientation);
        }
        
    }
    
}
